<?php
/**
 * +--------------------------------------------------------+
 * @Created by Phpstorm.
 * @Category BaseRepository.php
 * @Depiction
 * @Author hwy <429208948@qq.com>
 * @Date 2022/3/3  18:14
 * +--------------------------------------------------------+
 */

namespace App\Repositories;

use App\Exceptions\SystemException;
use Illuminate\Support\Facades\DB;

class BaseRepository
{
    protected $perPage = 10;

    /**
     * @param $params
     * @return int
     * @Depiction 每页数量
     * @Author hwy
     * @Date  2021/2/3  11:18
     */
    public function perPage($params)
    {
        return $perPage = empty($params['limit']) ? $this->perPage : $params['limit'];
    }

    /**
     * @param $params
     * @return array
     * @Depiction 获取列表时，请求的通用参数，统一组合
     * @Author hwy <429208948@qq.com>
     * @Date 2022/3/23  17:21
     */
    public function paramsSet($params)
    {
        $sort  = $params['sort'] ?? 'updated_at';
        $order = ($params['order'] ?? 'descending') === 'ascending' ? 'asc' : 'desc';

        return [$sort, $order];
    }

    /**
     * @param $multipleData
     * @param $tableName
     * @return int
     * @throws SystemException
     * @Depiction 批量删除
     * @Author hwy <429208948@qq.com>
     * @Date 2022/1/26  17:54
     */
    public function updateBatch($multipleData, $tableName)
    {
        try {
            if (empty($multipleData)) {
                throw new SystemException("数据不能为空");
            }

            $firstRow     = current($multipleData);
            $updateColumn = array_keys($firstRow);
            // 默认以id为条件更新，如果没有ID则以第一个字段为条件
            $referenceColumn = isset($firstRow['id']) ? 'id' : current($updateColumn);
            unset($updateColumn[0]);

            // 拼接sql语句
            $updateSql = "UPDATE " . $tableName . " SET ";
            $sets      = [];
            $bindings  = [];

            foreach ($updateColumn as $uColumn) {
                $setSql = "`" . $uColumn . "` = CASE ";
                foreach ($multipleData as $data) {
                    $setSql     .= "WHEN `" . $referenceColumn . "` = ? THEN ? ";
                    $bindings[] = $data[$referenceColumn];
                    $bindings[] = $data[$uColumn];
                }
                $setSql .= "ELSE `" . $uColumn . "` END ";
                $sets[] = $setSql;
            }

            $updateSql .= implode(', ', $sets);
            $whereIn   = collect($multipleData)->pluck($referenceColumn)->values()->all();
            $bindings  = array_merge($bindings, $whereIn);
            $whereIn   = rtrim(str_repeat('?,', count($whereIn)), ',');
            $updateSql = rtrim($updateSql, ", ") . " WHERE `" . $referenceColumn . "` IN (" . $whereIn . ")";
            // 传入预处理sql语句和对应绑定数据
            return DB::update($updateSql, $bindings);
        } catch (\Exception $e) {
            throw new SystemException($e->getMessage());
        }
    }

    public function commonCreate($add_data)
    {
        try {
            $add = $this->setting_config_tab->create($add_data);
        } catch (\Exception $e) {
            throw new SystemException($e->getMessage());
        }

        return $add;
    }

    public function commomDel($query, $ids)
    {
        if (is_string($ids)) {
            $ids = [$ids];
        }
        $data = $query->query()->whereIn('id', $ids)->get();
        if (empty($data)) {
            throw new SystemException('数据不存在');
        }
        DB::beginTransaction();
        foreach ($data as $value) {
            try {
                $del = $value->delete();
            } catch (\Exception $e) {
                DB::rollBack();
                throw new SystemException($e->getMessage());
            }
        }
        if ($del) {
            DB::commit();
            throw new SystemException('删除成功');
        } else {
            DB::rollBack();
            throw new SystemException('删除失败');
        }

    }
}
